<!-- 权限矩阵管理器组件 -->
<template>
  <div class="permission-matrix">
    <!-- 矩阵表格 -->
    <div class="matrix-table">
      <el-table
        :data="tableData"
        stripe
        border
        height="100%"
        class="permission-table"
        @selection-change="handleSelectionChange"
        @cell-click="handleCellClick"
      >
        <el-table-column type="selection" width="55" align="center" />
        
        <el-table-column 
          prop="name" 
          label="角色名称" 
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <div class="role-cell">
              <el-icon class="role-icon" :class="getRoleIconClass(row.role)">
                <component :is="getRoleIcon(row.role)" />
              </el-icon>
              <span class="role-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column 
          prop="dataAccess" 
          label="数据访问" 
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-switch
              v-model="row.permissions.dataAccess"
              @change="updatePermission(row, 'dataAccess', $event)"
              active-color="#67C23A"
              inactive-color="#DCDFE6"
            />
          </template>
        </el-table-column>

        <el-table-column 
          prop="systemConfig" 
          label="系统配置" 
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-switch
              v-model="row.permissions.systemConfig"
              @change="updatePermission(row, 'systemConfig', $event)"
              active-color="#67C23A"
              inactive-color="#DCDFE6"
            />
          </template>
        </el-table-column>

        <el-table-column 
          prop="userManagement" 
          label="用户管理" 
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-switch
              v-model="row.permissions.userManagement"
              @change="updatePermission(row, 'userManagement', $event)"
              active-color="#67C23A"
              inactive-color="#DCDFE6"
            />
          </template>
        </el-table-column>

        <el-table-column 
          prop="securityAudit" 
          label="安全审计" 
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-switch
              v-model="row.permissions.securityAudit"
              @change="updatePermission(row, 'securityAudit', $event)"
              active-color="#67C23A"
              inactive-color="#DCDFE6"
            />
          </template>
        </el-table-column>

        <el-table-column 
          label="权限等级" 
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="getPermissionLevelType(row)"
              size="small"
              class="permission-level-tag"
            >
              {{ getPermissionLevel(row) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column 
          label="最后修改"
          width="150"
          align="center"
        >
          <template #default="{ row }">
            <div class="last-modified">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(row.lastModified) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                size="small" 
                text 
                type="primary"
                @click="editRole(row)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                size="small" 
                text 
                type="info"
                @click="viewRoleDetails(row)"
              >
                <el-icon><View /></el-icon>
              </el-button>
              <el-button 
                size="small" 
                text 
                type="danger"
                @click="deleteRole(row)"
                v-if="!row.isSystem"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 快速操作栏 -->
    <div class="matrix-actions">
      <div class="action-left">
        <el-button size="small" @click="addNewRole">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
        <el-button size="small" @click="batchEdit" :disabled="selectedRoles.length === 0">
          <el-icon><EditPen /></el-icon>
          批量编辑
        </el-button>
        <el-button size="small" @click="exportMatrix">
          <el-icon><Download /></el-icon>
          导出矩阵
        </el-button>
      </div>

      <div class="action-right">
        <div class="permission-stats">
          <span class="stat-item">
            <el-icon><User /></el-icon>
            角色总数: {{ tableData.length }}
          </span>
          <span class="stat-item">
            <el-icon><Key /></el-icon>
            已选择: {{ selectedRoles.length }}
          </span>
        </div>
      </div>
    </div>

    <!-- 角色详情弹窗 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="dialogTitle"
      width="50vw"
      :before-close="handleDialogClose"
    >
      <div class="role-form" v-if="currentRole">
        <el-form :model="currentRole" label-width="100px" class="role-detail-form">
          <el-form-item label="角色名称">
            <el-input v-model="currentRole.name" :disabled="currentRole.isSystem" />
          </el-form-item>
          
          <el-form-item label="角色类型">
            <el-select v-model="currentRole.role" :disabled="currentRole.isSystem">
              <el-option label="指挥员" value="commander" />
              <el-option label="操作员" value="operator" />
              <el-option label="观察员" value="observer" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </el-form-item>

          <el-form-item label="权限配置">
            <div class="permission-checkboxes">
              <el-checkbox 
                v-model="currentRole.permissions.dataAccess"
                label="数据访问权限"
              />
              <el-checkbox 
                v-model="currentRole.permissions.systemConfig"
                label="系统配置权限"
              />
              <el-checkbox 
                v-model="currentRole.permissions.userManagement"
                label="用户管理权限"
              />
              <el-checkbox 
                v-model="currentRole.permissions.securityAudit"
                label="安全审计权限"
              />
            </div>
          </el-form-item>

          <el-form-item label="描述信息">
            <el-input
              v-model="currentRole.description"
              type="textarea"
              :rows="3"
              placeholder="请输入角色描述..."
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Clock,
  Edit,
  View,
  Delete,
  Plus,
  EditPen,
  Download,
  User,
  Key,
  UserFilled,
  Monitor,
  View as ViewIcon
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  matrixData: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['roleChanged', 'permissionUpdated'])

// 响应式数据
const tableData = ref([])
const selectedRoles = ref([])
const roleDialogVisible = ref(false)
const currentRole = ref(null)
const isEditing = ref(false)

// 初始化表格数据
const initTableData = (data) => {
  tableData.value = data.map(item => ({
    ...item,
    lastModified: item.lastModified || new Date(),
    isSystem: ['commander', 'operator'].includes(item.role),
    description: item.description || ''
  }))
}

// 计算属性
const dialogTitle = computed(() => {
  return isEditing.value ? '编辑角色' : '新增角色'
})

// 监听props变化
watch(() => props.matrixData, (newData) => {
  initTableData(newData)
}, { immediate: true, deep: true })

// 角色图标相关
const getRoleIcon = (role) => {
  const iconMap = {
    commander: UserFilled,
    operator: Monitor,
    observer: ViewIcon,
    admin: User
  }
  return iconMap[role] || User
}

const getRoleIconClass = (role) => {
  return `role-icon-${role}`
}

// 权限等级相关
const getPermissionLevel = (row) => {
  const permissions = row.permissions
  const totalPermissions = Object.keys(permissions).length
  const grantedPermissions = Object.values(permissions).filter(Boolean).length
  
  if (grantedPermissions === totalPermissions) return '最高'
  if (grantedPermissions >= totalPermissions * 0.75) return '高'
  if (grantedPermissions >= totalPermissions * 0.5) return '中'
  if (grantedPermissions > 0) return '低'
  return '无'
}

const getPermissionLevelType = (row) => {
  const level = getPermissionLevel(row)
  const typeMap = {
    '最高': 'danger',
    '高': 'warning',
    '中': 'primary',
    '低': 'info',
    '无': ''
  }
  return typeMap[level] || 'info'
}

// 权限更新
const updatePermission = (row, permission, value) => {
  row.permissions[permission] = value
  row.lastModified = new Date()
  
  emit('permissionUpdated', {
    role: row.role,
    permission,
    value,
    roleData: row
  })
  
  ElMessage.success(`${row.name} 的 ${getPermissionLabel(permission)} 权限已${value ? '开启' : '关闭'}`)
}

const getPermissionLabel = (permission) => {
  const labelMap = {
    dataAccess: '数据访问',
    systemConfig: '系统配置',
    userManagement: '用户管理',
    securityAudit: '安全审计'
  }
  return labelMap[permission] || permission
}

// 表格事件处理
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

const handleCellClick = (row, column, cell, event) => {
  // 点击单元格的处理逻辑
}

// 角色操作
const editRole = (row) => {
  currentRole.value = { ...row }
  isEditing.value = true
  roleDialogVisible.value = true
}

const viewRoleDetails = (row) => {
  currentRole.value = { ...row }
  isEditing.value = false
  roleDialogVisible.value = true
}

const deleteRole = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除角色 "${row.name}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.role === row.role)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('角色删除成功')
      emit('roleChanged', { type: 'delete', role: row })
    }
  } catch {
    // 用户取消
  }
}

const addNewRole = () => {
  currentRole.value = {
    role: '',
    name: '',
    permissions: {
      dataAccess: false,
      systemConfig: false,
      userManagement: false,
      securityAudit: false
    },
    description: '',
    isSystem: false,
    lastModified: new Date()
  }
  isEditing.value = false
  roleDialogVisible.value = true
}

const saveRole = () => {
  if (!currentRole.value.name || !currentRole.value.role) {
    ElMessage.warning('请填写完整的角色信息')
    return
  }

  if (isEditing.value) {
    // 更新现有角色
    const index = tableData.value.findIndex(item => item.role === currentRole.value.role)
    if (index > -1) {
      tableData.value[index] = { ...currentRole.value, lastModified: new Date() }
      ElMessage.success('角色更新成功')
      emit('roleChanged', { type: 'update', role: currentRole.value })
    }
  } else {
    // 新增角色
    const newRole = { ...currentRole.value, lastModified: new Date() }
    tableData.value.push(newRole)
    ElMessage.success('角色创建成功')
    emit('roleChanged', { type: 'create', role: newRole })
  }

  roleDialogVisible.value = false
}

const handleDialogClose = (done) => {
  done()
}

// 批量操作
const batchEdit = () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请先选择要编辑的角色')
    return
  }
  ElMessage.info('批量编辑功能开发中...')
}

const exportMatrix = () => {
  const matrixData = {
    roles: tableData.value,
    exportTime: new Date().toISOString(),
    totalRoles: tableData.value.length
  }

  const dataStr = JSON.stringify(matrixData, null, 2)
  const blob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)

  const link = document.createElement('a')
  link.href = url
  link.download = `permission_matrix_${Date.now()}.json`
  link.click()

  URL.revokeObjectURL(url)
  ElMessage.success('权限矩阵已导出')
}

// 工具函数
const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  if (props.matrixData.length === 0) {
    // 如果没有传入数据，使用默认数据
    initTableData([
      {
        role: 'commander',
        name: '指挥员',
        permissions: {
          dataAccess: true,
          systemConfig: true,
          userManagement: true,
          securityAudit: true
        }
      },
      {
        role: 'operator',
        name: '操作员',
        permissions: {
          dataAccess: true,
          systemConfig: false,
          userManagement: false,
          securityAudit: false
        }
      }
    ])
  }
})
</script>

<style scoped>
.permission-matrix {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 1.5vh;
}

.matrix-table {
  flex: 1;
  overflow: hidden;
}

/* 表格样式 */
.permission-table {
  height: 100%;
}

.role-cell {
  display: flex;
  align-items: center;
  gap: 0.5vw;
}

.role-icon {
  font-size: 1.2rem;
}

.role-icon-commander {
  color: #E6A23C;
}

.role-icon-operator {
  color: #409EFF;
}

.role-icon-observer {
  color: #67C23A;
}

.role-icon-admin {
  color: #F56C6C;
}

.role-name {
  font-weight: 600;
}

.permission-level-tag {
  font-weight: 600;
}

.last-modified {
  display: flex;
  align-items: center;
  gap: 0.3vw;
  font-size: 0.75rem;
  color: #8591a3;
}

.action-buttons {
  display: flex;
  gap: 0.5vw;
}

/* 快速操作栏 */
.matrix-actions {
  height: 5vh;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 1vw;
  background: #1f2d3d;
  border: 1px solid #2d3a4b;
  border-radius: 0.5vh;
}

.action-left {
  display: flex;
  gap: 1vw;
}

.action-right {
  display: flex;
  align-items: center;
}

.permission-stats {
  display: flex;
  gap: 2vw;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  font-size: 0.8rem;
  color: #bfcbd9;
}

/* 角色详情弹窗 */
.role-form {
  padding: 1vh;
}

.permission-checkboxes {
  display: flex;
  flex-direction: column;
  gap: 1vh;
}

.permission-checkboxes .el-checkbox {
  margin: 0;
}

/* Element Plus 表格深色主题 */
.permission-matrix :deep(.el-table) {
  background: #263445 !important;
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-table th) {
  background: #1f2d3d !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-table td) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #2d3a4b !important;
}

.permission-matrix :deep(.el-table__body tr:hover > td) {
  background: #2d3a4b !important;
}

.permission-matrix :deep(.el-switch) {
  --el-switch-on-color: #67C23A;
  --el-switch-off-color: #DCDFE6;
}

.permission-matrix :deep(.el-checkbox__label) {
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-form-item__label) {
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-input__wrapper) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  box-shadow: 0 0 0 1px #2d3a4b inset !important;
}

.permission-matrix :deep(.el-input__inner) {
  background: #263445 !important;
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-textarea__inner) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-select .el-input__wrapper) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
}

.permission-matrix :deep(.el-dialog) {
  background: #263445 !important;
  border: 1px solid #2d3a4b !important;
}

.permission-matrix :deep(.el-dialog__header) {
  background: #1f2d3d !important;
  border-bottom: 1px solid #2d3a4b !important;
}

.permission-matrix :deep(.el-dialog__title) {
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-dialog__body) {
  background: #263445 !important;
  color: #bfcbd9 !important;
}

.permission-matrix :deep(.el-dialog__footer) {
  background: #1f2d3d !important;
  border-top: 1px solid #2d3a4b !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .permission-checkboxes {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .matrix-actions {
    flex-direction: column;
    height: auto;
    padding: 1vh;
    gap: 1vh;
  }
  
  .action-left, .action-right {
    width: 100%;
    justify-content: center;
  }
}
</style>